pacman::p_load(sf, spdep, GWmodel, SpatialML,
tmap, rsample, Metrics, tidyverse,
knitr, kableExtra, jsonlite)Take Home Exercise 3
Part 1 : Data And Packages
Packages
Data
We can get the lat long data from the previous output
location_data <- read_rds("data/processed_data/coords.rds")
resale_data <- read_csv("data/resale.csv")Rows: 192970 Columns: 11
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (8): month, town, flat_type, block, street_name, storey_range, flat_mode...
dbl (3): floor_area_sqm, lease_commence_date, resale_price
ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
resale_tidy <- resale_data %>%
mutate(address = paste(block,street_name)) %>%
mutate(remaining_lease_yr = as.integer(
str_sub(remaining_lease, 0, 2)))%>%
mutate(remaining_lease_mth = as.integer(
str_sub(remaining_lease, 9, 11)))We also got data from the other required decision parameters, which are :
Structural factors
- Area of the unit
- Floor level Remaining
- lease
- Age of the unit
Locational factors
- Proxomity to CBD
- Proximity to eldercare
- Proximity to foodcourt/hawker centres
- Proximity to MRT
- Proximity to park
- Proximity to good primary school ( All schools are good schools lol)
- Proximity to shopping mall
- Proximity to supermarket
- Numbers of kindergartens within 350m
- Numbers of childcare centres within 350m
- Numbers of bus stop within 350m
- Numbers of primary school within 1km
CBD_lat_long <- c(1.287953, 103.851784) # Taken from https://www.latlong.net/place/downtown-core-singapore-20616.html
CBD_svy21 <- st_sfc(st_point(c(103.851784, 1.287953)),
crs = 4326) %>%
st_transform(3414)
eldercare_data <- st_read(dsn = "data/EldercareServicesSHP",
layer = "ELDERCARE") %>% st_transform(3414)Reading layer `ELDERCARE' from data source
`C:\Users\Admin\Desktop\SMU\ISSS626\ISSS626-KierenChua\TakeHomeEx\TakeHomeEx03\data\EldercareServicesSHP'
using driver `ESRI Shapefile'
Simple feature collection with 133 features and 18 fields
Geometry type: POINT
Dimension: XY
Bounding box: xmin: 14481.92 ymin: 28218.43 xmax: 41665.14 ymax: 46804.9
Projected CRS: SVY21
foodcourt_data <- st_read("data/HawkerCentresGEOJSON.geojson") %>% st_transform(3414)Reading layer `HawkerCentresGEOJSON' from data source
`C:\Users\Admin\Desktop\SMU\ISSS626\ISSS626-KierenChua\TakeHomeEx\TakeHomeEx03\data\HawkerCentresGEOJSON.geojson'
using driver `GeoJSON'
Simple feature collection with 125 features and 2 fields
Geometry type: POINT
Dimension: XYZ
Bounding box: xmin: 103.6974 ymin: 1.272716 xmax: 103.9882 ymax: 1.449017
z_range: zmin: 0 zmax: 0
Geodetic CRS: WGS 84
MRT_data <- st_read("data/LTAMRTStationExitGEOJSON.geojson") %>% st_transform(3414)Reading layer `LTAMRTStationExitGEOJSON' from data source
`C:\Users\Admin\Desktop\SMU\ISSS626\ISSS626-KierenChua\TakeHomeEx\TakeHomeEx03\data\LTAMRTStationExitGEOJSON.geojson'
using driver `GeoJSON'
Simple feature collection with 563 features and 2 fields
Geometry type: POINT
Dimension: XYZ
Bounding box: xmin: 103.6368 ymin: 1.264972 xmax: 103.9893 ymax: 1.449157
z_range: zmin: 0 zmax: 0
Geodetic CRS: WGS 84
park_data <- st_read("data/Parks.kml") %>% st_transform(3414)Reading layer `NATIONALPARKS' from data source
`C:\Users\Admin\Desktop\SMU\ISSS626\ISSS626-KierenChua\TakeHomeEx\TakeHomeEx03\data\Parks.kml'
using driver `KML'
Simple feature collection with 430 features and 2 fields
Geometry type: POINT
Dimension: XYZ
Bounding box: xmin: 103.6929 ymin: 1.214491 xmax: 104.0538 ymax: 1.462094
z_range: zmin: 0 zmax: 0
Geodetic CRS: WGS 84
primarySchool_data <- st_read("data/LTASchoolZone.geojson") %>% st_transform(3414)Reading layer `LTASchoolZone' from data source
`C:\Users\Admin\Desktop\SMU\ISSS626\ISSS626-KierenChua\TakeHomeEx\TakeHomeEx03\data\LTASchoolZone.geojson'
using driver `GeoJSON'
Simple feature collection with 211 features and 2 fields
Geometry type: MULTIPOLYGON
Dimension: XY, XYZ
Bounding box: xmin: 103.687 ymin: 1.272736 xmax: 103.9668 ymax: 1.457587
z_range: zmin: 0 zmax: 0
Geodetic CRS: WGS 84
Warning in CPL_transform(x, crs, aoi, pipeline, reverse, desired_accuracy, :
GDAL Message 1: Sub-geometry 0 has coordinate dimension 2, but container has 3
Warning in CPL_transform(x, crs, aoi, pipeline, reverse, desired_accuracy, :
GDAL Message 1: Sub-geometry 1 has coordinate dimension 2, but container has 3
mall_data <- st_read(dsn = "data/MP14SDCPPWPLANMallandPromenadeSHP",
layer="G_MP14_PKWB_MALL_PROM_PL") %>% st_transform(3414)Reading layer `G_MP14_PKWB_MALL_PROM_PL' from data source
`C:\Users\Admin\Desktop\SMU\ISSS626\ISSS626-KierenChua\TakeHomeEx\TakeHomeEx03\data\MP14SDCPPWPLANMallandPromenadeSHP'
using driver `ESRI Shapefile'
Simple feature collection with 464 features and 8 fields
Geometry type: MULTIPOLYGON
Dimension: XY
Bounding box: xmin: 15576.2 ymin: 24936 xmax: 40537.72 ymax: 48239.39
Projected CRS: SVY21
supermarket_data <- st_read("data/SupermarketsGEOJSON.geojson") %>% st_transform(3414)Reading layer `SupermarketsGEOJSON' from data source
`C:\Users\Admin\Desktop\SMU\ISSS626\ISSS626-KierenChua\TakeHomeEx\TakeHomeEx03\data\SupermarketsGEOJSON.geojson'
using driver `GeoJSON'
Simple feature collection with 526 features and 2 fields
Geometry type: POINT
Dimension: XYZ
Bounding box: xmin: 103.6258 ymin: 1.24715 xmax: 104.0036 ymax: 1.461526
z_range: zmin: 0 zmax: 0
Geodetic CRS: WGS 84
kindergarten_data <- st_read("data/Kindergartens.geojson") %>% st_transform(3414)Reading layer `Kindergartens' from data source
`C:\Users\Admin\Desktop\SMU\ISSS626\ISSS626-KierenChua\TakeHomeEx\TakeHomeEx03\data\Kindergartens.geojson'
using driver `GeoJSON'
Simple feature collection with 448 features and 2 fields
Geometry type: POINT
Dimension: XYZ
Bounding box: xmin: 103.6887 ymin: 1.247759 xmax: 103.9717 ymax: 1.455452
z_range: zmin: 0 zmax: 0
Geodetic CRS: WGS 84
childcare_data <- st_read("data/ChildCareServices.geojson") %>% st_transform(3414)Reading layer `ChildCareServices' from data source
`C:\Users\Admin\Desktop\SMU\ISSS626\ISSS626-KierenChua\TakeHomeEx\TakeHomeEx03\data\ChildCareServices.geojson'
using driver `GeoJSON'
Simple feature collection with 1925 features and 2 fields
Geometry type: POINT
Dimension: XYZ
Bounding box: xmin: 103.6878 ymin: 1.247759 xmax: 103.9897 ymax: 1.462134
z_range: zmin: 0 zmax: 0
Geodetic CRS: WGS 84
busstop_data <- st_read(dsn = "data/BusStopLocation_Jul2024",
layer= "BusStop") %>% st_transform(3414)Reading layer `BusStop' from data source
`C:\Users\Admin\Desktop\SMU\ISSS626\ISSS626-KierenChua\TakeHomeEx\TakeHomeEx03\data\BusStopLocation_Jul2024'
using driver `ESRI Shapefile'
Simple feature collection with 5166 features and 3 fields
Geometry type: POINT
Dimension: XY
Bounding box: xmin: 3970.122 ymin: 26482.1 xmax: 48285.52 ymax: 52983.82
Projected CRS: SVY21
Part 2 : Processing the data
Now we need to add all the data to the dataframe
Locations of HDB
We can use the location data and join by postal code
resale_tidy_loc <- left_join(resale_tidy, location_data, by = "address")
resale_tidy_clean <- resale_tidy_loc %>%
filter(!is.na(postal))
# Then we convert the lat long into SVY21
resale_sf <- st_as_sf(resale_tidy_clean,
coords = c("longitude", "latitude"),
crs = 4326) %>%
st_transform(3414)
# Handle the NA in the lease months
resale_sf$remaining_lease_mth[is.na(resale_sf$remaining_lease_mth)] <- 0We also need to jitter the points so that the points do not share the same coordinates, we need to jitter quite abit for the regression to work latter.
resale_sf$geometry <- st_jitter(resale_sf$geometry, amount = 100)We can now show the data
tmap_mode("plot")tmap mode set to plotting
tm_shape(resale_sf) +
tm_dots()
Unit Age
resale_sf$unit_age <- 99 - resale_sf$remaining_lease_yrProximity to CBD
We can compare all locations to the single CBD coordinate and output a distance
distance_matrix <- st_distance(resale_sf$geometry, CBD_svy21)
resale_sf$PROX_CBD <- apply(distance_matrix, 1, min)Proximity to Eldercare
In this case we can find the closest elder-care to the HDB unit
distance_matrix <- st_distance(resale_sf$geometry, eldercare_data$geometry)
resale_sf$PROX_ELDER <- apply(distance_matrix, 1, min)Proximity to Hawker Center
We do the same thing here
distance_matrix <- st_distance(resale_sf$geometry, foodcourt_data$geometry)
resale_sf$PROX_HAWKER <- apply(distance_matrix, 1, min)Proximity to MRT
distance_matrix <- st_distance(resale_sf$geometry, MRT_data$geometry)
resale_sf$PROX_MRT <- apply(distance_matrix, 1, min)Proximity to Park
distance_matrix <- st_distance(resale_sf$geometry, park_data$geometry)
resale_sf$PROX_PARK <- apply(distance_matrix, 1, min)Proximity to Primary School
We need to get the center of the primary school to compare against centroid. Need to drop the z value
primarySchool_data$geometry <- st_zm(primarySchool_data$geometry)
primarySchool_data$centroid <- st_centroid(primarySchool_data$geometry)
distance_matrix <- st_distance(resale_sf$geometry, primarySchool_data$centroid)
resale_sf$PROX_PRIM <- apply(distance_matrix, 1, min)Proximity to Shopping Mall
Same for the shopping mall
mall_data$centroid <- st_centroid(mall_data$geometry)
distance_matrix <- st_distance(resale_sf$geometry, mall_data$centroid)
resale_sf$PROX_MALL <- apply(distance_matrix, 1, min)Proximity to Supermarket
distance_matrix <- st_distance(resale_sf$geometry, supermarket_data$geometry)
resale_sf$PROX_SPMK <- apply(distance_matrix, 1, min)Number of Kindergartens within 350m
To calculate the number of kindergartens within 350m of the HBD, we need to have a 350m search radius around each location, then count the number of kindergartens within
distance_matrix <- st_distance(resale_sf$geometry, kindergarten_data$geometry)
count_within_350m <- apply(distance_matrix, 1, function(distances) {
sum(distances <= 350) # Count points within 350 meters
})
resale_sf$KIND_350 <- count_within_350mNumber of Childcares within 350m
distance_matrix <- st_distance(resale_sf$geometry, st_zm(childcare_data$geometry))
count_within_350m <- apply(distance_matrix, 1, function(distances) {
sum(distances <= 350) # Count points within 350 meters
})
resale_sf$CHILD_350 <- count_within_350mNumber of Bus-Stops within 350m
distance_matrix <- st_distance(resale_sf$geometry, busstop_data$geometry)
count_within_350m <- apply(distance_matrix, 1, function(distances) {
sum(distances <= 350) # Count points within 350 meters
})
resale_sf$BUS_350 <- count_within_350mNumber of Primary School within 1000m
distance_matrix <- st_distance(resale_sf$geometry, primarySchool_data$centroid)
count_within_1km <- apply(distance_matrix, 1, function(distances) {
sum(distances <= 1000) # Count points within 350 meters
})
resale_sf$PRI_1K <- count_within_1kmSaving the data
Now we can save the data for future purposes.
write_rds(resale_sf, "data/resale_sf_processed.rds")Part 3 : Shrinking the search space
Read the data
cleaned_resale_sf <- read_rds("data/resale_sf_processed.rds")
cleaned_resale_no_geom <- cleaned_resale_sf %>% st_drop_geometry()Because there is too much data, we will need to reduce the size of inspection. First we shall determine the types of flats available.
unique_flat_types <- unique(cleaned_resale_sf$flat_type)
unique_flat_types[1] "3 ROOM" "4 ROOM" "5 ROOM" "EXECUTIVE" "2 ROOM"
We also want to see the types of flats that are available
unique_flat_models <- unique(cleaned_resale_sf$flat_model)
unique_flat_models [1] "New Generation" "DBSS" "Improved"
[4] "Apartment" "Simplified" "Model A"
[7] "Model A-Maisonette" "Maisonette" "Standard"
[10] "Premium Apartment" "Type S1" "Model A2"
[13] "Type S2" "Adjoined flat" "Premium Apartment Loft"
[16] "2-room" "Premium Maisonette" "3Gen"
To have more focus on the data, we shall focus on the more expensive apartments vs the exercise given to us. To get an idea of what is expensive, we will need to see the spread of flat prices
boxplot(cleaned_resale_sf$resale_price, main="Box plot of resale prices", ylab="Resale Price")
We can see there are many outliers of data from the boxplot in the upper half. To maintain a large amount of data, we shall use the top 25% of data as the search space
sale_quantiles <- quantile(cleaned_resale_sf$resale_price)
sale_quantiles[4] 75%
629000
So the upper quantile is 629 000 dollars, we shall round that down to 600 000 and then only consider rooms above that price.
cleaned_resale_sf_cut <- cleaned_resale_sf %>%
filter(resale_price >= 6e5)
cleaned_resale_sf_cut_no_geom <- cleaned_resale_sf_cut %>%
st_drop_geometry()This leaves us with over 10000 data samples, which should be enough for us.
Part 4 : Computing Correlation Matrix
Bin the data
We need to bin some of the variables so that they make integers
Storeys
unqiue_storey <- unique(cleaned_resale_sf_cut_no_geom$storey_range)
storey_mapping <- setNames(seq_along(unqiue_storey), unqiue_storey)
cleaned_resale_sf_cut_no_geom$storey_range_bin <- storey_mapping[cleaned_resale_sf_cut_no_geom$storey_range]
cleaned_resale_sf_cut$storey_range_bin <- storey_mapping[cleaned_resale_sf_cut$storey_range]Plotting the graph
We are not sure if all the variables are correlated, so we can build a correlation matrix to see if we need to exclude any variables
required_cols <- c(7, 9, 13, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29)
corrplot::corrplot(cor(cleaned_resale_sf_cut_no_geom[, required_cols]),
diag = FALSE,
order = "AOE",
tl.pos = "td",
tl.cex = 0.5,
method = "number",
type = "upper")
We can see that lease commence date and lease remaining year has a correlation value of more than 0.8, so we can remove them from the choices
Variance Inflation Factor
We also can check the Variance Inflation Factor to see if there are any variables above a 5
Train-Test Split
First we need to do a train test split for any model training. Split shall be 65 - 35.
set.seed(1234)
# First we try to remove any NA values
cleaned_resale_sf_cut <- cleaned_resale_sf_cut[rowSums(is.na(st_drop_geometry(cleaned_resale_sf_cut))) == 0,, ]
resale_split <- initial_split(cleaned_resale_sf_cut,
prop = 6.5/10,)
# We use a 80/20 split since we have more than 40000 samples of data
train_data <- training(resale_split)Generating simple LM Model
price_mlr <- lm(resale_price ~ floor_area_sqm + storey_range_bin + remaining_lease_yr +
PROX_CBD + PROX_ELDER + PROX_HAWKER +
PROX_MRT + PROX_PARK + PROX_MALL +
PROX_SPMK + KIND_350 +
CHILD_350 + BUS_350 +
PRI_1K,
data=train_data)vif <- performance::check_collinearity(price_mlr)
kable(vif,
caption = "Variance Inflation Factor (VIF) Results") %>%
kable_styling(font_size = 18) | Term | VIF | VIF_CI_low | VIF_CI_high | SE_factor | Tolerance | Tolerance_CI_low | Tolerance_CI_high |
|---|---|---|---|---|---|---|---|
| floor_area_sqm | 2.123886 | 2.060393 | 2.191180 | 1.457356 | 0.4708351 | 0.4563750 | 0.4853442 |
| storey_range_bin | 1.036499 | 1.020201 | 1.065949 | 1.018086 | 0.9647858 | 0.9381311 | 0.9801993 |
| remaining_lease_yr | 1.871208 | 1.817733 | 1.928181 | 1.367921 | 0.5344141 | 0.5186236 | 0.5501359 |
| PROX_CBD | 2.378824 | 2.305242 | 2.456553 | 1.542344 | 0.4203759 | 0.4070745 | 0.4337938 |
| PROX_ELDER | 1.373721 | 1.340160 | 1.410593 | 1.172058 | 0.7279500 | 0.7089217 | 0.7461797 |
| PROX_HAWKER | 1.455691 | 1.418806 | 1.495825 | 1.206520 | 0.6869590 | 0.6685275 | 0.7048181 |
| PROX_MRT | 1.107995 | 1.086099 | 1.135459 | 1.052614 | 0.9025310 | 0.8807009 | 0.9207261 |
| PROX_PARK | 1.253436 | 1.224856 | 1.285648 | 1.119570 | 0.7978070 | 0.7778177 | 0.8164223 |
| PROX_MALL | 1.370811 | 1.337369 | 1.407568 | 1.170816 | 0.7294952 | 0.7104452 | 0.7477370 |
| PROX_SPMK | 1.116288 | 1.093951 | 1.143935 | 1.056545 | 0.8958264 | 0.8741753 | 0.9141179 |
| KIND_350 | 1.416146 | 1.380860 | 1.454700 | 1.190019 | 0.7061421 | 0.6874267 | 0.7241866 |
| CHILD_350 | 1.493679 | 1.455264 | 1.535336 | 1.222162 | 0.6694878 | 0.6513231 | 0.6871608 |
| BUS_350 | 1.165329 | 1.140608 | 1.194397 | 1.079504 | 0.8581267 | 0.8372425 | 0.8767257 |
| PRI_1K | 1.392592 | 1.358262 | 1.430211 | 1.180081 | 0.7180855 | 0.6991976 | 0.7362349 |
We can also plot this out for better visualization
plot(vif) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))Variable `Component` is not in your data frame :/

We can see that all the variables have a variables that is below a 5, so we can use all of them.
Part 5 : Generating Geographically Weighted Predictive Models
Convert to Spatial Datframe
# First we check for NA values in the traindata
train_data_sp <- as_Spatial(train_data)Get adaptive bandwidth
bw_adaptive <- bw.gwr(resale_price ~ floor_area_sqm +
storey_range_bin + remaining_lease_yr +
PROX_CBD + PROX_ELDER + PROX_HAWKER +
PROX_MRT + PROX_PARK + PROX_MALL +
PROX_SPMK + KIND_350 +
CHILD_350 + BUS_350 +
PRI_1K,
data=train_data_sp,
approach="CV",
kernel="gaussian",
adaptive=TRUE,
longlat=FALSE)Take a cup of tea and have a break, it will take a few minutes.
-----A kind suggestion from GWmodel development group
Adaptive bandwidth: 5848 CV score: 9.243392e+13
Adaptive bandwidth: 3622 CV score: 9.014497e+13
Adaptive bandwidth: 2245 CV score: 8.697263e+13
Adaptive bandwidth: 1395 CV score: 8.349133e+13
Adaptive bandwidth: 869 CV score: 7.899485e+13
Adaptive bandwidth: 544 CV score: 7.466116e+13
Adaptive bandwidth: 343 CV score: 7.086881e+13
Adaptive bandwidth: 219 CV score: 6.661355e+13
Adaptive bandwidth: 142 CV score: 6.541905e+13
Adaptive bandwidth: 94 CV score: 6.76693e+13
Adaptive bandwidth: 171 CV score: 6.621383e+13
Adaptive bandwidth: 123 CV score: 6.475166e+13
Adaptive bandwidth: 112 CV score: 6.437627e+13
Adaptive bandwidth: 104 CV score: 6.420869e+13
Adaptive bandwidth: 100 CV score: 6.410668e+13
Adaptive bandwidth: 97 CV score: 6.406601e+13
Adaptive bandwidth: 95 CV score: 3.245186e+32
Adaptive bandwidth: 98 CV score: 6.407292e+13
Adaptive bandwidth: 96 CV score: 6.400365e+13
Adaptive bandwidth: 95 CV score: 3.245186e+32
Adaptive bandwidth: 96 CV score: 6.400365e+13
We will also save it for the future
write_rds(bw_adaptive, "data/model/bw_adaptive.rds")bw_adaptive <- read_rds("data/model/bw_adaptive.rds")Make the model
Now we will make the adaptive GWR model
gwr_adaptive <- gwr.basic(formula = resale_price ~ floor_area_sqm +
storey_range_bin + remaining_lease_yr +
PROX_CBD + PROX_ELDER + PROX_HAWKER +
PROX_MRT + PROX_PARK + PROX_MALL +
PROX_SPMK + KIND_350 +
CHILD_350 + BUS_350 +
PRI_1K,
data=train_data_sp,
bw=bw_adaptive,
kernel = 'gaussian',
adaptive=TRUE,
longlat = FALSE)Save a copy
write_rds(gwr_adaptive, "data/model/gwr_adaptive.rds")Reading the model
gwr_adaptive <- read_rds("data/model/gwr_adaptive.rds")gwr_adaptive ***********************************************************************
* Package GWmodel *
***********************************************************************
Program starts at: 2024-11-04 10:54:08.130745
Call:
gwr.basic(formula = resale_price ~ floor_area_sqm + storey_range_bin +
remaining_lease_yr + PROX_CBD + PROX_ELDER + PROX_HAWKER +
PROX_MRT + PROX_PARK + PROX_MALL + PROX_SPMK + KIND_350 +
CHILD_350 + BUS_350 + PRI_1K, data = train_data_sp, bw = bw_adaptive,
kernel = "gaussian", adaptive = TRUE, longlat = FALSE)
Dependent (y) variable: resale_price
Independent variables: floor_area_sqm storey_range_bin remaining_lease_yr PROX_CBD PROX_ELDER PROX_HAWKER PROX_MRT PROX_PARK PROX_MALL PROX_SPMK KIND_350 CHILD_350 BUS_350 PRI_1K
Number of data points: 9451
***********************************************************************
* Results of Global Regression *
***********************************************************************
Call:
lm(formula = formula, data = data)
Residuals:
Min 1Q Median 3Q Max
-300000 -66120 -8029 54789 600034
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.118e+05 1.604e+04 6.971 3.37e-12 ***
floor_area_sqm 4.071e+03 7.401e+01 55.011 < 2e-16 ***
storey_range_bin 3.689e+03 3.407e+02 10.826 < 2e-16 ***
remaining_lease_yr 4.602e+03 1.217e+02 37.803 < 2e-16 ***
PROX_CBD -1.650e+01 3.508e-01 -47.031 < 2e-16 ***
PROX_ELDER 9.124e-01 2.428e+00 0.376 0.70705
PROX_HAWKER -2.515e+01 2.766e+00 -9.092 < 2e-16 ***
PROX_MRT -3.251e+01 3.103e+00 -10.474 < 2e-16 ***
PROX_PARK -1.287e+01 2.784e+00 -4.622 3.84e-06 ***
PROX_MALL -1.325e+01 1.038e+00 -12.766 < 2e-16 ***
PROX_SPMK 3.758e+01 7.310e+00 5.142 2.78e-07 ***
KIND_350 1.492e+02 1.115e+03 0.134 0.89358
CHILD_350 1.506e+03 5.591e+02 2.693 0.00709 **
BUS_350 2.600e+03 3.957e+02 6.571 5.25e-11 ***
PRI_1K -4.598e+03 7.453e+02 -6.169 7.15e-10 ***
---Significance stars
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 100400 on 9436 degrees of freedom
Multiple R-squared: 0.4302
Adjusted R-squared: 0.4293
F-statistic: 508.8 on 14 and 9436 DF, p-value: < 2.2e-16
***Extra Diagnostic information
Residual sum of squares: 9.517932e+13
Sigma(hat): 100364.1
AIC: 244536.8
AICc: 244536.8
BIC: 235346.7
***********************************************************************
* Results of Geographically Weighted Regression *
***********************************************************************
*********************Model calibration information*********************
Kernel function: gaussian
Adaptive bandwidth: 96 (number of nearest neighbours)
Regression points: the same locations as observations are used.
Distance metric: Euclidean distance metric is used.
****************Summary of GWR coefficient estimates:******************
Min. 1st Qu. Median 3rd Qu.
Intercept -2.2161e+08 -3.9447e+05 2.3362e+05 1.0175e+06
floor_area_sqm 5.7881e+02 3.0150e+03 4.4597e+03 6.4886e+03
storey_range_bin -1.0897e+04 -2.2363e+03 -4.0654e+02 2.3511e+03
remaining_lease_yr -4.5221e+04 -3.7742e+03 1.3836e+03 4.3692e+03
PROX_CBD -4.3089e+03 -5.8548e+01 -8.2466e+00 5.2746e+01
PROX_ELDER -1.2694e+04 -3.8395e+01 9.2124e+00 7.7290e+01
PROX_HAWKER -2.8057e+04 -9.5238e+01 -1.2423e+01 5.8582e+01
PROX_MRT -5.3975e+03 -7.1185e+01 -9.9480e+00 7.0932e+01
PROX_PARK -6.4208e+03 -1.4255e+02 -2.8937e+01 3.0632e+01
PROX_MALL -3.6982e+04 -1.4251e+02 -1.8509e+01 3.2341e+01
PROX_SPMK -1.6215e+03 -6.1334e+01 6.4511e+00 1.1628e+02
KIND_350 -3.7195e+05 -9.7700e+03 -2.6817e+03 8.0525e+03
CHILD_350 -4.3973e+04 -4.7274e+03 1.0222e+03 6.4265e+03
BUS_350 -2.6895e+04 -2.0684e+03 5.2201e+02 2.7924e+03
PRI_1K -8.5880e+05 -8.6240e+03 1.9411e+03 1.2431e+04
Max.
Intercept 39372792.4
floor_area_sqm 10209.9
storey_range_bin 14261.9
remaining_lease_yr 11105.9
PROX_CBD 32763.3
PROX_ELDER 2546.9
PROX_HAWKER 14993.8
PROX_MRT 8302.1
PROX_PARK 7010.7
PROX_MALL 5511.8
PROX_SPMK 36702.7
KIND_350 343934.6
CHILD_350 38966.2
BUS_350 23048.4
PRI_1K 291799.6
************************Diagnostic information*************************
Number of data points: 9451
Effective number of parameters (2trace(S) - trace(S'S)): 858.937
Effective degrees of freedom (n-2trace(S) + trace(S'S)): 8592.063
AICc (GWR book, Fotheringham, et al. 2002, p. 61, eq 2.33): 240309.3
AIC (GWR book, Fotheringham, et al. 2002,GWR p. 96, eq. 4.22): 239515.2
BIC (GWR book, Fotheringham, et al. 2002,GWR p. 61, eq. 2.34): 235646.4
Residual sum of squares: 5.221577e+13
R-square value: 0.6873985
Adjusted R-square value: 0.6561445
***********************************************************************
Program stops at: 2024-11-04 10:55:12.949854
From the results we can see that proximity to elder-care, number of child-cares and number of kindergartens seem to be insignificant to the resale price of the location. This could probably signify that these metrics may not be in consideration when people are making a purchase. We can try to remove its from future training.
Computer Test Data Adaptive Bandwidth
test_data <- testing(resale_split)
test_data_sp <- as_Spatial(test_data)gwr_bw_test_adaptive <- bw.gwr(resale_price ~ floor_area_sqm +
storey_range_bin + remaining_lease_yr +
PROX_CBD + PROX_ELDER + PROX_HAWKER +
PROX_MRT + PROX_PARK + PROX_MALL +
PROX_SPMK + KIND_350 +
CHILD_350 + BUS_350 +
PRI_1K,
data=test_data_sp,
approach="CV",
kernel="gaussian",
adaptive=TRUE,
longlat=FALSE)Take a cup of tea and have a break, it will take a few minutes.
-----A kind suggestion from GWmodel development group
Adaptive bandwidth: 3152 CV score: 5.095984e+13
Adaptive bandwidth: 1956 CV score: 4.955062e+13
Adaptive bandwidth: 1215 CV score: 4.78703e+13
Adaptive bandwidth: 759 CV score: 4.59419e+13
Adaptive bandwidth: 475 CV score: 4.374012e+13
Adaptive bandwidth: 301 CV score: 4.162405e+13
Adaptive bandwidth: 192 CV score: 3.970175e+13
Adaptive bandwidth: 126 CV score: 3.789844e+13
Adaptive bandwidth: 84 CV score: 3.633732e+13
Adaptive bandwidth: 59 CV score: 3.538126e+13
Adaptive bandwidth: 42 CV score: 3.505121e+13
Adaptive bandwidth: 33 CV score: 3.489163e+13
Adaptive bandwidth: 26 CV score: Inf
Adaptive bandwidth: 36 CV score: 3.48701e+13
Adaptive bandwidth: 39 CV score: 3.498059e+13
Adaptive bandwidth: 35 CV score: 3.486166e+13
Adaptive bandwidth: 33 CV score: 3.489163e+13
Adaptive bandwidth: 34 CV score: 3.492213e+13
Adaptive bandwidth: 33 CV score: 3.489163e+13
Adaptive bandwidth: 34 CV score: 3.492213e+13
Adaptive bandwidth: 33 CV score: 3.489163e+13
Adaptive bandwidth: 33 CV score: 3.489163e+13
Adaptive bandwidth: 32 CV score: 3.496297e+13
Adaptive bandwidth: 32 CV score: 3.496297e+13
Adaptive bandwidth: 31 CV score: 3.513044e+13
Adaptive bandwidth: 31 CV score: 3.513044e+13
Adaptive bandwidth: 30 CV score: 3.815501e+13
Adaptive bandwidth: 30 CV score: 3.815501e+13
Adaptive bandwidth: 29 CV score: 3.598842e+13
Adaptive bandwidth: 29 CV score: 3.598842e+13
Adaptive bandwidth: 28 CV score: Inf
Adaptive bandwidth: 28 CV score: Inf
Adaptive bandwidth: 27 CV score: 2.995955e+36
Adaptive bandwidth: 27 CV score: 2.995955e+36
Adaptive bandwidth: 26 CV score: Inf
Adaptive bandwidth: 26 CV score: Inf
Adaptive bandwidth: 25 CV score: Inf
Adaptive bandwidth: 25 CV score: Inf
Now we can run prediction on the test dataset
Running Predictions on the test data
st_crs(train_data_sp)Coordinate Reference System:
User input: SVY21 / Singapore TM
wkt:
PROJCRS["SVY21 / Singapore TM",
BASEGEOGCRS["SVY21",
DATUM["SVY21",
ELLIPSOID["WGS 84",6378137,298.257223563,
LENGTHUNIT["metre",1]]],
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433]],
ID["EPSG",4757]],
CONVERSION["Singapore Transverse Mercator",
METHOD["Transverse Mercator",
ID["EPSG",9807]],
PARAMETER["Latitude of natural origin",1.36666666666667,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8801]],
PARAMETER["Longitude of natural origin",103.833333333333,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8802]],
PARAMETER["Scale factor at natural origin",1,
SCALEUNIT["unity",1],
ID["EPSG",8805]],
PARAMETER["False easting",28001.642,
LENGTHUNIT["metre",1],
ID["EPSG",8806]],
PARAMETER["False northing",38744.572,
LENGTHUNIT["metre",1],
ID["EPSG",8807]]],
CS[Cartesian,2],
AXIS["northing (N)",north,
ORDER[1],
LENGTHUNIT["metre",1]],
AXIS["easting (E)",east,
ORDER[2],
LENGTHUNIT["metre",1]],
USAGE[
SCOPE["Cadastre, engineering survey, topographic mapping."],
AREA["Singapore - onshore and offshore."],
BBOX[1.13,103.59,1.47,104.07]],
ID["EPSG",3414]]
#gwr_pred <- gwr.predict(formula = resale_price ~ floor_area_sqm +
# storey_range_bin + remaining_lease_yr +
# PROX_CBD + PROX_ELDER + PROX_HAWKER +
# PROX_MRT + PROX_PARK + PROX_MALL +
# PROX_SPMK + KIND_350 +
# CHILD_350 + BUS_350 +
# PRI_1K,
# data= train_data_sp,
# predictdata = test_data_sp,
# bw=bw_adaptive,
# kernel = 'gaussian',
# adaptive= TRUE,
# longlat = FALSE)Part 7 : Generating Random Forest Model
Now we can move on to creating the random forest model
coords_train <- st_coordinates(train_data)
coords_test <- st_coordinates(test_data)
train_data_nogeom <- train_data %>%
st_drop_geometry()After preparing the data, we can train the model below
Basic Random Forest
set.seed(1234)
rf <- ranger(resale_price ~ floor_area_sqm +
storey_range_bin + remaining_lease_yr +
PROX_CBD + PROX_ELDER + PROX_HAWKER +
PROX_MRT + PROX_PARK + PROX_MALL +
PROX_SPMK + KIND_350 +
CHILD_350 + BUS_350 +
PRI_1K,
data=train_data_nogeom)We can view the model output below
rfRanger result
Call:
ranger(resale_price ~ floor_area_sqm + storey_range_bin + remaining_lease_yr + PROX_CBD + PROX_ELDER + PROX_HAWKER + PROX_MRT + PROX_PARK + PROX_MALL + PROX_SPMK + KIND_350 + CHILD_350 + BUS_350 + PRI_1K, data = train_data_nogeom)
Type: Regression
Number of trees: 500
Sample size: 9451
Number of independent variables: 14
Mtry: 3
Target node size: 5
Variable importance mode: none
Splitrule: variance
OOB prediction error (MSE): 5023645049
R squared (OOB): 0.7157895
Cleaning up the data
The code now is taking up alot of space, so we nedd to clean up some of the data that we dont need for future
rm(rf)
rm(price_mlr)
rm(resale_split)
rm(gwr_adaptive)
rm(busstop_data)
rm(childcare_data)
rm(cleaned_resale_no_geom)
rm(cleaned_resale_sf)
rm(eldercare_data)
rm(foodcourt_data)
rm(kindergarten_data)
rm(mall_data)
rm(MRT_data)
rm(primarySchool_data)Geographically weighted Random Forest
set.seed(1234)
gwRF_adaptive <- grf(formula = resale_price ~ floor_area_sqm +
storey_range_bin + remaining_lease_yr +
PROX_CBD + PROX_ELDER + PROX_HAWKER +
PROX_MRT + PROX_PARK + PROX_MALL +
PROX_SPMK + KIND_350 +
CHILD_350 + BUS_350 +
PRI_1K,
dframe=train_data_nogeom,
bw=bw_adaptive,
kernel="adaptive",
coords=coords_train)
Number of Observations: 9451
Number of Independent Variables: 14
Kernel: Adaptive
Neightbours: 96
--------------- Global ML Model Summary ---------------
Ranger result
Call:
ranger(resale_price ~ floor_area_sqm + storey_range_bin + remaining_lease_yr + PROX_CBD + PROX_ELDER + PROX_HAWKER + PROX_MRT + PROX_PARK + PROX_MALL + PROX_SPMK + KIND_350 + CHILD_350 + BUS_350 + PRI_1K, data = train_data_nogeom, num.trees = 500, mtry = 4, importance = "impurity", num.threads = NULL)
Type: Regression
Number of trees: 500
Sample size: 9451
Number of independent variables: 14
Mtry: 4
Target node size: 5
Variable importance mode: impurity
Splitrule: variance
OOB prediction error (MSE): 4612949806
R squared (OOB): 0.7390244
Importance:
floor_area_sqm storey_range_bin remaining_lease_yr PROX_CBD
2.977832e+13 1.195320e+13 1.593509e+13 3.526793e+13
PROX_ELDER PROX_HAWKER PROX_MRT PROX_PARK
7.796038e+12 9.779579e+12 8.871637e+12 8.831199e+12
PROX_MALL PROX_SPMK KIND_350 CHILD_350
1.344756e+13 6.735692e+12 1.891701e+12 3.445535e+12
BUS_350 PRI_1K
3.599768e+12 4.718909e+12
Mean Square Error (Not OOB): 909027101.367
R-squared (Not OOB) %: 94.857
AIC (Not OOB): 194984.146
AICc (Not OOB): 194984.196
--------------- Local Model Summary ---------------
Residuals OOB:
Min. 1st Qu. Median Mean 3rd Qu. Max.
-665000.0 -43548.6 -5918.9 -596.7 36662.9 432645.5
Residuals Predicted (Not OOB):
Min. 1st Qu. Median Mean 3rd Qu. Max.
-122863.1 -5467.1 -499.7 128.3 4456.8 164455.1
Local Variable Importance:
Min Max Mean StD
floor_area_sqm 1777954668 2.643120e+12 249085148532 286894587946
storey_range_bin 1321337404 5.600684e+11 61059195013 73326417657
remaining_lease_yr 633108120 1.027629e+12 138330018917 136874478584
PROX_CBD 4317027703 7.754116e+11 67033814042 58945224069
PROX_ELDER 3670833577 4.819070e+11 63884116919 47372929863
PROX_HAWKER 4351101712 1.134055e+12 66358702105 72657028429
PROX_MRT 4066713291 5.941267e+11 68159755980 63690255509
PROX_PARK 4416339936 8.330187e+11 64655468635 56254087077
PROX_MALL 4132483593 5.948118e+11 63897456639 54633020764
PROX_SPMK 4954693397 6.562553e+11 64878360646 56103764598
KIND_350 0 9.685132e+10 5981484288 8332343133
CHILD_350 0 1.973514e+11 18822223674 17860270451
BUS_350 2018011859 2.991237e+11 26645196055 24357940617
PRI_1K 0 1.792149e+11 7900229926 11992377320
Mean squared error (OOB): 5827964401.412
R-squared (OOB) %: 67.025
AIC (OOB): 212544.559
AICc (OOB): 212544.609
Mean squared error Predicted (Not OOB): 164582017.25
R-squared Predicted (Not OOB) %: 99.069
AIC Predicted (Not OOB): 178832.709
AICc Predicted (Not OOB): 178832.76
Calculation time (in seconds): 39.8701
We can then save the model for future use
write_rds(gwRF_adaptive, "data/model/gwRF_adaptive.rds")We then re-read it, mostly for running purposes
gwRF_adaptive <- read_rds("data/model/gwRF_adaptive.rds")Predicting with test data
test_data_nogeom <- cbind(
test_data, coords_test) %>%
st_drop_geometry()gwRF_pred <- predict.grf(gwRF_adaptive,
test_data_nogeom,
x.var.name="X",
y.var.name="Y",
local.w=1,
global.w=0)GRF_pred_df <- as.data.frame(gwRF_pred)
test_data_pred <- cbind(test_data,
GRF_pred_df)Save the data for the future
write_rds(test_data_pred, "data/test_results.rds")test_data_pred <- read_rds( "data/test_results.rds")Freeing Memory
The model is very large >15Gb so once we got th results, we should free up the memory
rm(gwRF_adaptive)Viewing Random Forest Prediction Error
Now we can compare the diffrence in values from predictions vs actual resale value by locaiton
rmse(test_data_pred$resale_price,
test_data_pred$gwRF_pred)[1] 73299.75
ggplot(data = test_data_pred,
aes(x = gwRF_pred,
y = resale_price)) +
geom_point()
We can see that there is a bottom out on the predictions, which is due to us cutting off the resale price limit at 600,000.
Show residuals
test_data_pred$residuals <- test_data_pred$gwRF_pred - test_data_pred$resale_price
st_crs(test_data_pred)Coordinate Reference System:
User input: EPSG:3414
wkt:
PROJCRS["SVY21 / Singapore TM",
BASEGEOGCRS["SVY21",
DATUM["SVY21",
ELLIPSOID["WGS 84",6378137,298.257223563,
LENGTHUNIT["metre",1]]],
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433]],
ID["EPSG",4757]],
CONVERSION["Singapore Transverse Mercator",
METHOD["Transverse Mercator",
ID["EPSG",9807]],
PARAMETER["Latitude of natural origin",1.36666666666667,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8801]],
PARAMETER["Longitude of natural origin",103.833333333333,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8802]],
PARAMETER["Scale factor at natural origin",1,
SCALEUNIT["unity",1],
ID["EPSG",8805]],
PARAMETER["False easting",28001.642,
LENGTHUNIT["metre",1],
ID["EPSG",8806]],
PARAMETER["False northing",38744.572,
LENGTHUNIT["metre",1],
ID["EPSG",8807]]],
CS[Cartesian,2],
AXIS["northing (N)",north,
ORDER[1],
LENGTHUNIT["metre",1]],
AXIS["easting (E)",east,
ORDER[2],
LENGTHUNIT["metre",1]],
USAGE[
SCOPE["Cadastre, engineering survey, topographic mapping."],
AREA["Singapore - onshore and offshore."],
BBOX[1.13,103.59,1.47,104.07]],
ID["EPSG",3414]]
# Load in the mpsz data
mpsz = st_read(dsn = "data/geospatial", layer = "MP14_SUBZONE_WEB_PL") %>% st_transform(3414)Reading layer `MP14_SUBZONE_WEB_PL' from data source
`C:\Users\Admin\Desktop\SMU\ISSS626\ISSS626-KierenChua\TakeHomeEx\TakeHomeEx03\data\geospatial'
using driver `ESRI Shapefile'
Simple feature collection with 323 features and 15 fields
Geometry type: MULTIPOLYGON
Dimension: XY
Bounding box: xmin: 2667.538 ymin: 15748.72 xmax: 56396.44 ymax: 50256.33
Projected CRS: SVY21
Plot the map
tmap_mode("view")tmap mode set to interactive viewing
tm_shape(mpsz) +
tmap_options(check.and.fix = TRUE) +
tm_polygons(alpha = 0.4) +
tm_shape(test_data_pred) +
tm_dots(col = "residuals",
alpha = 0.6,
style = "quantile")Warning: The shape mpsz is invalid (after reprojection). See sf::st_is_valid
Variable(s) "residuals" contains positive and negative values, so midpoint is set to 0. Set midpoint = NA to show the full spectrum of the color palette.
tmap_mode("plot")tmap mode set to plotting